/**
* @Description: 客户管理(客户)-列表
* @author  tangbin
* @date 2023/4/18
*/

<template>
  <div class="app-containers">
    <query-table-render
        ref="queryTable"
        :query-model="queryModel"
        :table-request="requestTableData"
        :table-column="tableColumns"
        :toolbar-render="toolbarRnd"
        :transform-query="transformQuery"
        :title-render="titleRender"
        @on-operator="onOperator"
        :show-table-batch-view="showTableBatchView"
    >
      <template v-slot:form>
        <!-- :filter-method="tenantNameFilter" 
            @focus="tenantNameFocus" -->
        <el-form-item label="渠道名称" prop="tenantId">
          <el-select v-model="queryModel.tenantId" placeholder="请选择" style="width:100%" 
            clearable filterable 
            
          >
            <el-option
              v-for="item in channelInfos"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="客户编码" prop="code">
          <el-input v-model="queryModel.code" placeholder="请输入" clearable @keyup.enter.native="searchListQuery"/>
        </el-form-item>
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="queryModel.name" placeholder="请输入" clearable @keyup.enter.native="searchListQuery"/>
        </el-form-item>
        <el-form-item label="客户类型" prop="type">
          <el-select v-model="queryModel.type" placeholder="请选择" style="width:100%" clearable>
            <el-option
              v-for="item in customerTypeOptions"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="telephone">
          <el-input v-model="queryModel.telephone" placeholder="请输入" clearable @keyup.enter.native="searchListQuery"/>
        </el-form-item>
        <el-form-item label="客户状态" prop="status">
          <el-select v-model="queryModel.status" placeholder="请选择" style="width:100%" clearable>
            <el-option
              v-for="item in dict.type.basic_data_tenant_customer_status"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
      </template>
    </query-table-render>
  </div>
</template>


<script>
import {checkPermi} from '@/utils/permission.js'
import QueryTableRender from "@/components/QueryTableRender";
import {tenantOptions, tenantCustomerList, customerTypeList} from '@/api/basic/tenantCustomer.js'
import {toThousandFilter} from '@/utils/index.js'
import BigNumber from 'bignumber.js'

export default {
  name: "CustomersManage",
  dicts: ['basic_data_tenant_customer_type', 'basic_data_tenant_customer_status'],  // 客户类型 客户状态
  components: {QueryTableRender},
  data() {
    return {
      queryModel: {}, // 查询参数
      tableColumns: [], // 列表
      channelInfos: [], // 渠道名称
      channelInfosCopy: [], // 渠道名称copy
      bookkeepingOptions: [{label: '是', value: 'Y'}, {label: '否', value: 'N'}], // 是否记账 N否；Y是
      // customerTypeOptions: [{label: '个人', value: 1}, {label: '单位', value: 2}], // 客户类型
      customerStatusOptions: [{label: '未支付', value: 1}], // 客户状态
      customerTypeOptions: [], // 客户类型列表
      showTableBatchView: false, // 是否显示批量视图
    }
  },
  created() {
    this.setupQueryModel();
    this.setupTableColumns();
  },
  mounted() {
    this.getTenantOptions();
    this.getCustomerTypeList();
  },
  activated() {
    this.getTenantOptions(); // 渠道列表
    this.getCustomerTypeList(); // 客户类型列表
  },
  watch: {
    $route(route) {
      if (route.name == 'CustomersManage') {
        this.onRefreshTable();
      }
    },
  },
  methods: {
    /**
     * 初始化查询参数
     */
     setupQueryModel() {
      this.queryModel = {
        tenantId: undefined, // 渠道名称
        code: undefined, // 客户编码
        name: undefined, // 客户名称
        type: undefined, // 客户类型
        telephone: undefined, // 联系电话
        customerStatus: undefined, // 客户状态
      };
    },

    setupTableColumns() {
      this.tableColumns = [
        {
          width: '60',
          type: 'selection',
          align: 'center',
        },
        {
          label: '序号',
          width: '60',
          type: 'index',
          increment: true
        },
        {
          prop: 'code',
          label: '客户编码',
          minWidth: '160',
        },
        {
          prop: 'name',
          label: '客户名称',
          minWidth: '160',
          showOverflowTooltip: true,
        },
        {
          prop: 'type',
          label: '客户类型',
          minWidth: '130',
          render: (h, text) => {
            let show = text;
            this.dict.type.basic_data_tenant_customer_type.some((item) => {
              if (item.value === text) {
                show = item.label;
                return true;
              }
            });
            return show;
          }
        },
        {
          prop: 'telephone',
          label: '联系电话',
          minWidth: '120',
        },
        {
          prop: 'distributionLimit',
          label: '铺货额度',
          minWidth: '120',
          render: (h, text) => {
            return this.getAmountFormatter(text);
          }
          // toThousandFilter
        },
        {
          prop: 'accounting',
          label: '是否记账',
          minWidth: '100', // bookkeepingOptions
          render: (h, text) => {
            let show = text;
            this.bookkeepingOptions.some((item) => {
              if (item.value === text) {
                show = item.label;
                return true;
              }
            });
            return show;
          }
        },
        {
          prop: 'discount',
          label: '折扣',
          minWidth: '80',
          render: (h, text) => {
            if ((text == undefined || text == '' || text == null) && text !== 0) {
              return text;
            }
            return text + '%';
          }
        },
        {
          prop: 'status',
          label: '客户状态',
          minWidth: '100',
          render: (h, text) => {
            let show = text;
            this.dict.type.basic_data_tenant_customer_status.some((item) => {
              if (item.value === text) {
                show = item.label;
                return true;
              }
            });
            return show;
          }
        },
        {
          prop: 'tenantName',
          label: '渠道名称',
          minWidth: '180',
          showOverflowTooltip: true,
        },
        {
          label: '操作',
          width: '130',
          type: 'operator',
          align: "left",
          fixed: 'right',
          operators: record => { return this.operatorsFunc(record)}
        },
      ]  
    },

    /**
     * 查询列表
     * @param {*} queryParams
     */
     requestTableData(queryParams) {
      return tenantCustomerList(queryParams).then(respData => {
        return {
          success: true,
          total: respData.data.total,
          data: respData.data.records,
        }
      });
    },

    /**
     * 金额格式化
     */
     getAmountFormatter(value) {
      if (value === undefined || value === null || value === '') {
        return '';
      }
      let tm = new BigNumber(value);
      return toThousandFilter(tm.toFixed(2));
    },

    /**
     * 刷新列表
     */
    onRefreshTable(){
      this.$refs['queryTable'].refreshTable()
    },

    /**
     * 渲染功能列表
     * @param {*} h 
     */
    toolbarRnd(h){
      let list = [];
      if (checkPermi(['basic-data:tenant-customer:export'])) {
        list.push(<el-button type="primary" plain icon="el-icon-download" size="small" vOn:click={() => this.handleExport()}>导出</el-button>);
      }
      if (checkPermi(['basic-data:tenant-customer:add'])) {
        list.push(<el-button type="primary" icon="el-icon-plus" vOn:click={() => this.onAdd()}>新增</el-button>);
      }
      
      return list;
    },

    operatorsFunc(record) {
      let list = [];
      if (checkPermi(['basic-data:tenant-customer:detail'])) {
        list.push({label: '详情', command: 'detail'});
      }
      // console.log('record=', record);
      // 自建的客户，租户支持修改 -- 有修改按钮
      // 修改：数据行租户ID(渠道名称ID)与客户登录账号的租户ID，一致的时候可以修改，不一致(智科账号登录)不可以修改
      // synchronizeFlag true接口同步 false系统自建
      if (checkPermi(['basic-data:tenant-customer:update']) && record.tenantId == this.$store.getters.tenantId && record.synchronizeFlag == false) {
        list.push({label: '修改', command: 'edit'});
      }
      
      return list;
   },

    /**
     * 标题渲染
     * @param {*} h 
     */
    titleRender(h) {
      return <div>
        <span style="display:inline-block; background-color: #1890FF;margin-bottom: -2px; margin-right: 8px; width: 3px; height: 14px"></span>
        <span style="display: inline-block; color: #333333; font-size: 16px;">客户列表</span>
      </div>;
    },

    /**
     * 搜索列表查询
     */
     searchListQuery() {
      this.$refs['queryTable'].submitQuery();
    },

    /**
     * 修改参数格式
     * @param {*} queryData 
     */
    transformQuery(queryData) {
      let transParams = {}
      for (let keyName in queryData) {
          transParams[keyName] = queryData[keyName]
      }
      return transParams
    },

    /**
     * 操作页面
     * @param {*} command 
     * @param {*} record 
     */
    onOperator(command, record) {
      let query = {
        id: record.id,
      };
      if (command == 'edit') {
        this.$router.push({path: 'CustomersManageEdit', query: query});
      } else if (command == 'detail') {
        this.$router.push({path: 'CustomersManageDetail', query: query});
      }
    },

    /**
     * 新增
     */
    onAdd() {
      this.$router.push({path: 'CustomersManageAdd'});
    },

    /**
     * 导出
     */
    handleExport() {

      const selectedList = this.$refs['queryTable'].getSelection();
      let list = [];
      if (selectedList && selectedList.length > 0) {
        list = selectedList.map(item => {
          return item.id
        });
      }
      // console.log('list=', list);
      let param = {};
      if (list.length > 0) {
        param =  {ids: list};
      } else {
        param = JSON.parse(JSON.stringify(this.queryModel));
        delete param.pageNum;
        delete param.pageSize;
      }
      let date = this.$moment(new Date()).format("YYYY-MM-DD");
      this.downloadFile('/basic/data/tenant/customer/export', param, `客户管理_${date}.xlsx`)
    },

    /**
     * 客户类型列表
     */
    getCustomerTypeList() {
      customerTypeList().then(res => {
        console.log('res=', res);
        if (res.code == 200) {
          this.customerTypeOptions = res.data;
        }
      }).catch(err => {

      });
    },

    /**
     * 输入渠道名称为得到焦点调用
     * @param {*} e 
     */
     tenantNameFocus(e) {
      this.channelInfos = this.channelInfosCopy;
    },

    /**
     * 渠道名称筛选
     * @param {*} val 
     */
    tenantNameFilter(val) {
      if (val) {
        this.channelInfos = this.channelInfosCopy.filter((item) => {
          if (!!~item.name.indexOf(val)) {
            return true;
          }
        });
        if (this.channelInfos && this.channelInfos.length == 1) {
          this.$nextTick(() => {
            this.queryModel.tenantId = this.channelInfos[0].id;
          });
        } else {
          this.queryModel.tenantId = undefined;
        }
      } else {
        this.channelInfos = this.channelInfosCopy;
      }
    },

    /**
     * 获取渠道列表
     */
    getTenantOptions() {
      tenantOptions().then(res => {
        if (res.code == 200) {
          this.channelInfos = res.data;
        }
      }).catch(err => {

      });
    },

  },
}
</script>


<style lang="scss" scoped>
</style>